#define _GLOBAL_VAR_
#include "Global.h"
#include "HardWare.h"
#include "timer.h"
#include "IR_Funcion.h"
#include "LED.h"
#include "OPA.h"
#include "UART.h"
#include "ADC.h"
#include "UserApp.h"
#include "MotorDev.h"

uint8 CntFlashTime;
bit F_IR_CHANGE; 
bit F_One_Second;

void main()
{
	if((_pdf == TRUE) && (_to == TRUE)) //
	{		
		//---- WDT Wakeup ----//	  			  			
		GCC_CLRWDT();
		//  P_TEST2 = 1;
	}	 
	else
	{
		// vuint8 i;

		//---- System Reset ----//
		SystemClockConfigure();

		IO_Init();									/*IO initial*/
		DelayXmSec(50*T1MS);						/*delay 50ms*/ 
		Clear_RamInit();							/*clear RAM*/
#ifdef _UART_EN_
		initUART();
#endif
		initADC();
		init_IRFunction();

		// LED_Flash(5);
		LED_ON();
		DelayXmSec(500*T1MS);
		LED_OFF();


		// timebase0_configure();						/*timebase parameters configure*/								
												
		_emi = NO;								/*interrupt enable*/

		MotorDev_HardwareConfig();
		F_STATE_VALVE = 1;
    	F_IR_CHANGE = NO;
		// CloseValve();

		initUserApp();
	}

	while(1)
	{
		_tb0f = 0;
		GCC_CLRWDT();

		F_One_Second = ~F_One_Second;

		if(IR_RemoteDetect())
		{
			DoCommand();
		}
		else
		{
			if(IR_Detect())
			{
				if(F_IR_CHANGE == 0)
				{
					F_IR_CHANGE = 1;
					// CntFlashTime = 0;
					F_One_Second = 0;
				}
				// if(CntFlashTime == 0)
				if(F_One_Second == 0)
				{
					LED_ON();
					if(F_LowPower == NO)
						DelayXmSec(10*T1MS);
					else
					{
						DelayXmSec(5*T1MS);
						LED_OFF();
						DelayXmSec(40*T1MS);
						LED_ON();
						DelayXmSec(5*T1MS);
						LED_OFF();
						DelayXmSec(40*T1MS);
						LED_ON();
						DelayXmSec(5*T1MS);
					}
					LED_OFF();
				}
			}
			else
			{
				F_IR_CHANGE = 0;
			}
			// CntFlashTime++;
			// if(CntFlashTime >= 2)
			if(F_One_Second == 0)
			{
				// CntFlashTime = 0;
				Action_Proc();
				LowPowerCheck();
			}
		}

		//---- 检测按键 ----//
		if(P_KEY == LOW)
		{
			DelayXmSec(20*T1MS);
			if(P_KEY == LOW)
			{
				OpenValve();
				DelayXmSec(6000*T1MS);
				CloseValve();
			}
		}

		_tbon = 0;
		_wdtc = C_TM_WDTC_512MS;	//			//	
		// _wdtc = C_TM_WDTC_128MS;	//128ms				//	
		// P_TEST2 = 0;	
		GCC_HALT();								//		
		GCC_NOP();
		GCC_NOP();
		GCC_NOP();
		GCC_NOP();

	}
}